package org.xxpay.boot.card.common;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.stereotype.Component;
import org.xxpay.dal.dao.card.FieldAnnotation;
import org.xxpay.dal.dao.card.model.SaScoreFlow;
import org.xxpay.dal.dao.card.model.SaSettleConfig;

@Component
public class CommonUtils<T> {
	
	@Resource
	private HttpServletResponse response;
	
	/**
	 * 生成卡号
	 * @return
	 */
	public String randomCard(){
		return  "CD"+String.valueOf(System.currentTimeMillis()).substring(8);
	}
	
	/**
	 * 生成交易记录号
	 * @return
	 */
	public String randomDeal(){
		return  "DL"+String.valueOf(System.currentTimeMillis());
	}
	
	/**
	 * 生成交易记录号
	 * @return
	 */
	public String randomBill(){
		return  "BL"+String.valueOf(System.currentTimeMillis());
	}
	
	/**
	 * 检查传入的对象是否有空值，存在空值返回属性名称
	 * @return
	 */
	public String checkIsNull(Object obj){
        Class userCla = (Class) obj.getClass();
        Field[] fs = userCla.getDeclaredFields();
        for (int i = 0; i < fs.length; i++) {
            Field f = fs[i];
            f.setAccessible(true); 
            Object val = new Object();
            try {
                val = f.get(obj);
                if(val == null && !ignore(f.getName())){
                	return f.getName();
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        }
        return "notNull";
	}
	
	/**
	 * 判断字符串是否为空
	 * @return
	 */
	public boolean isNull(String id){
		if(id == null || id.equals(" ")){
			return true;
		}
		return false;
	}
	
	/**
	 * 获得PageBean返回结果
	 * @param start
	 * @param end
	 * @param total
	 * @param list
	 * @return
	 */
	public PageBean getInstance(int start,int end,int total,List list){
		PageBean pageBean = new PageBean();
		Page<T> page = new Page<T>(start,end,total,list);
		pageBean.setTotal(page.getTotal());
		pageBean.setList(list);
		return pageBean;
	}
	
	/**
	 * 导出或下载Excel表
	 * @param list
	 * @param excelName
	 */
	public void importExcel(List list,String excelName){
		// 第一步，创建一个webbook，对应一个Excel文件
		HSSFWorkbook wb = new HSSFWorkbook();
		
		// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet    
        HSSFSheet sheet = wb.createSheet(excelName);
        
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short    
        HSSFRow row = sheet.createRow(0);
        
        // 第四步，创建单元格，并设置值表头 设置表头居中    
        HSSFCellStyle style = wb.createCellStyle(); 
        style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
        
        HSSFCell cell = null;
        
        // 第五步，写入实体数据 实际应用中这些数据从数据库得到，    
        for (int i = 0; i < list.size(); i++){  
        	
        	if(i == 0){
        		Class clazz = list.get(i).getClass();
    	        Field[] fs = clazz.getDeclaredFields();
    	        for (int x = 0; x < fs.length; x++) {
    	            Field f = fs[x];
    	            f.setAccessible(true); 
    	            FieldAnnotation fa = f.getAnnotation(FieldAnnotation.class);
    	            try {
    	            	 if(fa == null){
    					 }else{
    						 cell = row.createCell(x);
    						 cell.setCellValue(fa.name());    
    						 cell.setCellStyle(style);    
    					 }
    	            } catch (IllegalArgumentException e) {
    	                e.printStackTrace();
    	            }
    	        }
        	}
            row = sheet.createRow(i + 1);    
            Class clazz = list.get(i).getClass();
            Object o = list.get(i);
            Field[] fss = clazz.getDeclaredFields();
            for (int j = 0; j < fss.length; j++) {
            	Field f = fss[j];
            	f.setAccessible(true); 
            	FieldAnnotation fa = f.getAnnotation(FieldAnnotation.class);
                String name = f.getName();  
                name = name.substring(0, 1).toUpperCase() + name.substring(1);  
				try {
					Method m = clazz.getMethod("get" + name);
					Object value = m.invoke(o);
					if(fa == null){
					}else{
						cell = row.createCell(j);
						if(value == null){
							cell.setCellValue("");    
						}else{
							cell.setCellValue(value.toString());
						}
						cell.setCellStyle(style);
					}
				} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
					e.printStackTrace();
				}  
            }
        }    
        
        // 第六步，将文件存到指定位置    
       /* try    
        {    
            FileOutputStream fout = new FileOutputStream("C:/Users/Administrator/Desktop/导出结果.xls");    
            wb.write(fout);    
            fout.close();    
        }    
        catch (Exception e)    
        {    
            e.printStackTrace();    
        }  */
        
        // 第六步，下载  
        OutputStream out = null;    
        try {        
            out = response.getOutputStream();    
            String fileName = excelName+".xls";// 文件名    
            response.setContentType("application/x-msdownload");    
            response.setHeader("Content-Disposition", "attachment; filename="    
                                                    + URLEncoder.encode(fileName, "UTF-8"));    
            wb.write(out);    
        } catch (Exception e) {    
            e.printStackTrace();    
        } finally {      
            try {       
                out.close();      
            } catch (IOException e) {      
                e.printStackTrace();    
            }      
        }     
	}
	
	/**
	 * 
	 * 获取出账日
	 * @param list
	 * @return
	 */
	public String getDate(List<SaSettleConfig> list){
		String str = "";
		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH)+1;
		int date = calendar.get(Calendar.DATE); 
		SaSettleConfig saSettleConfig = list.get(0);
		if(saSettleConfig.getLiquidateMode() == '1'){
			int day = saSettleConfig.getLiquidateDate();
			if(date < day){
				if(month == 12){
					str = (year+1)+"/"+1+"/"+day;
				}else{
					str = year+"/"+month+"/"+day;
				}
			}else{
				if(month == 12){
					str = (year+1)+"/"+1+"/"+day;
				}else{
					str = year+"/"+(month+1)+"/"+day;
				}
			}
		}
		return str;
	}
	
	/**
	 * 对一些属性值跳过
	 * @return
	 */
	public boolean ignore(String name){
		
		if("isDelete".equalsIgnoreCase(name)){
			return true;
		}
		
		if("flag".equalsIgnoreCase(name)){
			return true;
		}
		
		if("status".equalsIgnoreCase(name)){
			return true;
		}
		
		if("userId".equalsIgnoreCase(name)){
			return true;
		}
		
		if("cardNumber".equalsIgnoreCase(name)){ //卡号(交易记录)
			return true;
		}
		 
		if("dealRecordId".equalsIgnoreCase(name)){ //交易记录ID(交易记录)
			return true;
		}
		
		if("calculateTime".equalsIgnoreCase(name)){ //清算时间(订单)
			return true;
		} 
		
		if("dealCreateTime".equalsIgnoreCase(name)){ //交易创建时间(订单)
			return true;
		}
		
		if("dealEndTime".equalsIgnoreCase(name)){ //交易完成时间(订单)
			return true;
		}
		
		if("dealOrderId".equalsIgnoreCase(name)){ //订单ID(订单)
			return true;
		}
		
		if("scoreFlowId".equalsIgnoreCase(name)){ //积分流水ID(积分流水)
			return true;
		}
		
		if("scoreFlowNumber".equalsIgnoreCase(name)){ //积分流水ID(积分流水)
			return true;
		}
		
		return false;
	}
	
}
